import { defineStore } from 'pinia'
import { post } from '@/untils/request'
import cookie from 'js-cookie'
import router from "@/router"//引入路由
import { ElMessage } from 'element-plus'//引入消息弹出框

export const useUsertore = defineStore({
  id: 'useUsertore',
  persist: {
    paths: ['user']//paths判断需要存储的字段
  },//开启状态持久化
  state: () => ({
    user: new UserInfo(),//用户信息
    token: new UserToken(),//token头
    loginInfo:new UserLogin()//拦截器，设置无痛刷新请求登录的数据
  }),
  actions: {
    //设置用户信息
    setUser(user: UserInfo) {
      this.user = user;
    },
    //设置token
    setToken(token: UserToken) {
      this.token = token;
    },
    logout() {//退出登录
      let datas = {
        _gp: 'admin',
        _mt: 'logout',
        ADMINTOKEN: ''
      }

      post({}, datas).then((res: any) => {
        console.log(res, 444);
        let { errmsg, errno } = res
        if (200 == errno) {
          cookie.remove('token')//删除cookie
          localStorage.removeItem('useUsertore')//清空用户个人信息
          router.replace('/login')//跳转登录页面
          ElMessage.success('退出成功')
        } else {
          router.replace('/login')//跳转登录页面
          ElMessage.error(errmsg)
        }
      }).catch(err => {
        console.log(err);
      })
    }
  }
})
class UserInfo {//定义数据类型，声明数组类型的默认是空数组[],声明数字类型的默认是0,声明字符串类型的默认为空字符串''
  avatarUrl?: string;
  gmtCreate: number;
  gmtLastLogin: string;
  gmtUpdate: number;
  id: number;
  lastLoginIp: string;
  perms: string[];
  phone: number;
  realname: string;
  roleIds: number[];
  roles: string[];
  status: number;
  username: string;
  constructor() {
    this.avatarUrl = '';
    this.gmtCreate = 0;
    this.gmtLastLogin = '';
    this.gmtUpdate = 0;
    this.id = 0;
    this.lastLoginIp = '';
    this.perms = [];
    this.phone = 0;
    this.realname = '';
    this.roleIds = [];
    this.roles = [];
    this.status = 0;
    this.username = '';
  }
}
class UserLogin {
  username: string;
  password: string;
  constructor() {
    this.username = '';
    this.password = '';
  }
}
class UserToken {
  token: string
  constructor() {
    this.token = '';
  }
}